import serial
import time
import json
from setting import logger
from ble_function import BleFunction

from change_ip import change_ip

from queue import Queue

from auto_ip import get_network_info

class BleSentry:

    def __init__(self) -> None:
        
        self.ser = serial.Serial('/dev/ttyS5', 9600)

        self.task_queue = Queue(100)

    
    def start_ble_server(self):

        receive_str = ""

        while True:

            try:

                data = self.ser.read(self.ser.in_waiting).decode()

            except Exception as e:

                logger.error(str(e))

            else:

                if data.startswith("##"):

                    receive_str = ""

                receive_str += data


                if data.endswith("##"):

                    self.task_queue.put(receive_str.replace(" ", ""))

                    logger.info("添加蓝牙任务：")
                    logger.info(receive_str)

    def ble_send(self, data):
        '''蓝牙发送数据'''

        data = "##" + json.dumps(data) + "##"

        logger.info("蓝牙发送信息：")

        logger.info(data)

        self.ser.write(data.encode())

        
    def task_worker(self):

        while True:
            try:

                task = self.task_queue.get()

                task = json.loads(task.replace("##", ""))

            except Exception as e:

                logger.error("处理任务：")
                logger.error(task)
                logger.error(str(e))

            else:

                logger.info("处理任务：")
                logger.info(task)

                self.processing_tasks(task)

    def processing_tasks(self, task): # 任务处理

        if task["task_type"] == "set_host": # 设置主站ip

            '''
            {
                "task_type": "set_host",
                "task_id": "2",	# 任务ID号
                "data": {
                    "host": "192.168.33.33",
                    "netmask": "255.255.255.0"
                }
            }
            '''

            host = task["data"]["host"]

            netmask =  task["data"]["netmask"]

            l = host.split(".")

            l[-1] = "1"

            gateway = '.'.join(l)

            send_data = {
                "type": "callback", 
                "data": {
                    "task_type": "set_host", 
                    "task_id": task["task_id"], 
                    "result": "success"
                }
            }

            self.ble_send(send_data) # 回调信息

            time.sleep(5)

            change_ip(host, netmask, gateway)

        if task["task_type"] == "get_base_info": # 获取基站信息

            '''{
                "task_type": "get_base_info",
                "task_id": "2",	# 任务ID号
                "data": ""
            }'''

            send_data = BleFunction().get_base_info(task)

            logger.info(send_data)

            self.ble_send(send_data) # 回调信息

        if task["task_type"] == "get_sensor_info": # 获取基站信息
            '''
            {
                "task_type": "get_sensor_info",
                "task_id": "2",	# 任务ID号
                "data": {"base_station_id": 1}
            }
            '''
            send_data = BleFunction().get_sensor_info(task)

            logger.info(send_data)

            self.ble_send(send_data) # 回调信息

        
        if task["task_type"] == "get_task_status": # 获取对应的任务状态

            '''
            {
                "task_type": "get_task_status",
                "task_id": "2",	# 任务ID号
            }
            '''

            send_data = BleFunction().get_task_status(task)

            logger.info(send_data)

            self.ble_send(send_data) # 回调信息

        if task["task_type"] == "get_ip": # 获取对应的任务状态

            '''
            {
                "task_type": "get_ip",
                "task_id": "2",	# 任务ID号
            }
            '''

            send_data = get_network_info()

            logger.info(send_data)

            self.ble_send(send_data) # 回调信息



        
        if task["task_type"] in ["set_acquisition_cycle", "read_acquisition_cycle", "set_reporting_cycle", "read_reporting_cycle", "set_fluctuation_threshold", "read_fluctuation_threshold", "set_alarm_threshold", "read_alarm_threshold"]:
            '''
            {
                "task_type": "set_acquisition_cycle",													
                "task_id": "183",																		# 任务ID号
                "data": {
                    "devaddr_list": ["943EBDE7", "92B18DD5"],
                    "value": "00"  # 00:不采集; 01:连续采集; 02:1秒一次; 03:5秒一次; 04:10秒一次； 05：30秒一次； 
                }
            }
            '''


            send_data = BleFunction().order_insert(task)



            logger.info(send_data)

            self.ble_send(send_data) # 回调信息




        






        


if __name__ == "__main__":

    from threading import Thread

    bs = BleSentry()

    Thread(target=bs.task_worker).start() # 开启消费线程

    bs.start_ble_server()








# ser = serial.Serial('/dev/ttyS5', 9600)

# file = None

# try:
#     with open('ble_ip_data', 'w') as file:
#         while True:

#             data = ser.read(ser.in_waiting)


#             if data:
#                 print(data.decode())

#                 if data.startswith(b"##"):
#                     ip_address = data[2:].decode()
#                     print("IP地址:",ip_address)

 
#                     with open('ip_data','w') as file: 
#                         file.write(ip_address)
#                         file.flush()
          
#                     with open('ip_data','r') as read_file:  
#                         file_content = read_file.read().strip()
#                         ser.write(file_content.encode())

#                 if data==b'**0101': 
#                     with open('ip_data','r') as read_file:
#                         file_content = read_file.read().strip()
#                         ser.write(file_content.encode())

#                 # if data==b'**0102':
#                 #     with open('/root/.master_station_ip','r') as file:
#                 #         file_content = file.read().strip()
#                 #         ser.write(file_content.encode())
                
#                 else:
#                     print("无效数据")
 

# except KeyboardInterrupt:

#     ser.close()
#     file.close()
